#include "qiniuconfig.h"
#include <QByteArray>
#include <QDebug>

QiniuConfig::QiniuConfig()
{
    // 初始化默认配置
    m_accessKey = "DfQxFZO0zlHJe-kNOFcIKLTL-RZ-OSQtRdj5EA2C";
    m_secretKey = "CyuB9MHjjx5_0w9odKZ4XBeu_v8MrjxAsbGStnwA";
    m_bucket = "malloyserver";
    m_region = "z2";  // 华南区域
}

QString QiniuConfig::getUploadToken()
{
    // 构建上传策略
    QJsonObject putPolicy;
    putPolicy["scope"] = m_bucket;

    // 设置凭证有效期为1小时（3600秒）
    qint64 deadline = QDateTime::currentDateTime().toSecsSinceEpoch() + 3600;
    putPolicy["deadline"] = deadline;

    // 将上传策略转换为JSON字符串
    QJsonDocument doc(putPolicy);
    QByteArray putPolicyJson = doc.toJson(QJsonDocument::Compact);

    // Base64编码上传策略
    QByteArray encodedPutPolicy = putPolicyJson.toBase64();

    // 使用SecretKey对编码后的上传策略进行HMAC-SHA1签名
    QByteArray sign = QMessageAuthenticationCode::hash(
                encodedPutPolicy,
                m_secretKey.toUtf8(),
                QCryptographicHash::Sha1);

    // Base64编码签名
    QByteArray encodedSign = sign.toBase64();

    // 拼接上传凭证
    QString uploadToken = m_accessKey + ":" + encodedSign + ":" + encodedPutPolicy;

    return uploadToken;
}

void QiniuConfig::setAccessKey(const QString &key)
{
    m_accessKey = key;
}

void QiniuConfig::setSecretKey(const QString &key)
{
    m_secretKey = key;
}

void QiniuConfig::setBucket(const QString &bucket)
{
    m_bucket = bucket;
}

void QiniuConfig::setRegion(const QString &region)
{
    m_region = region;
}

QString QiniuConfig::getAccessKey() const
{
    return m_accessKey;
}

QString QiniuConfig::getSecretKey() const
{
    return m_secretKey;
}

QString QiniuConfig::getBucket() const
{
    return m_bucket;
}

QString QiniuConfig::getRegion() const
{
    return m_region;
}

QString QiniuConfig::getUploadDomain() const
{
    // 根据区域代码返回对应的上传域名
    if (m_region == "z0") {
        return "https://up.qiniup.com";  // 华东区域
    } else if (m_region == "z1") {
        return "https://up-z1.qiniup.com";  // 华北区域
    } else if (m_region == "z2") {
        return "https://up-z2.qiniup.com";  // 华南区域
    } else if (m_region == "na0") {
        return "https://up-na0.qiniup.com";  // 北美区域
    } else if (m_region == "as0") {
        return "https://up-as0.qiniup.com";  // 东南亚区域
    } else {
        return "https://up.qiniup.com";  // 默认使用华东区域
    }
}

QString QiniuConfig::getAccessDomain() const
{
    // 返回默认的访问域名，实际应用中可能需要自定义
    return "http://" + m_bucket + ".qiniudn.com";
}
